package com.one.common.core.util;

import com.one.common.core.constants.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Map;
public class JwtUtils {
    /**
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret)
    {
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }
    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }
    /**
     * 获取到token中的userKey
     * @param claims
     * @return
     */
    public static String getUserKey(Map<String, Object> claims){
        return toStr(claims.get(JwtConstants.userKey));
    }
    /**
     * 获取到token中的userId
     * @param claims
     * @return
     */
    public static String getUserId(Map<String, Object> claims){
        return toStr(claims.get(JwtConstants.userId));
    }

    private static String toStr(Object value) {
        if(value == null){
            return "";
        }
        return value.toString();
    }

    public static void main(String[] args) {
//        Map<String, Object> claims = new HashMap<>();
//        LoginTestDTO loginTestDTO = new LoginTestDTO();
//        loginTestDTO.setUserAccount("zaq");
//        claims.put("userId",loginTestDTO);
//        String secret = "asbsqacxkjhnghiojnjkdnv";
//        String token = createToken(claims,secret);
//        System.out.println(token);

        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOnsidXNlckFjY291bnQiOiJ6YXEiLCJwYXNzd29yZCI6bnVsbH19.kMqx3BYqmL-8V-l6-6VZ4dmkAjD2jWowDwlKvcSr1wwEbx5vRX6gRUnvu643UT508VXzgZWEP4cctnDSkKFbww";
        String secret = "asbsqacxkjhnghiojnjkdnv";

        Claims claims = parseToken(token,secret);
        System.out.println(claims.get("userId"));
    }
}
